/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package main;

import java.io.IOException;
import java.io.DataInputStream;

/**
 *
 * @author daz
 */
public class ReaderThread implements Runnable {

    private static final int THREAD_DELAY = 10;
    private DataInputStream dataInput;
    private DataTransfer connectionHadler;
    private boolean isRunning;
    private byte testOnline;
    private byte endByte;
    private boolean isDipose;

    public ReaderThread(DataInputStream in, DataTransfer handler) {
        this.dataInput = in;
        this.connectionHadler = handler;
        isRunning = true;
        isDipose = false;
        Thread thread = new Thread(this);
        thread.start();
    }

    private void parseDataReceive() throws Exception {
        if (dataInput.available() > 0) {
            int dataLength = this.dataInput.available();
            //TODO: count kb
            byte[] data = new byte[dataLength];
            this.dataInput.read(data, 0, dataLength);
            if (testOnline == 125) {
                int startByte = 0;
                for (int i = 0; i < dataLength; i++) {
                    if (data[i] == 38) {
                        byte[] buffer = new byte[i - startByte];
                        System.arraycopy(data, startByte, buffer, 0, buffer.length);
                        String message = new String(buffer, "UTF-8");
                        // Debug.d("message :" + message);
                        connectionHadler.dataInputQueue.addElement(message);
                        if (i != dataLength - 1) {
                            if (data[i + 1] == 125) {
                                startByte = i + 2;
                            }
                        }
                    }
                }
            }
        }
    }

    public void run() {
        while (isRunning) {
            try {
                Thread.sleep(THREAD_DELAY);
                testOnline = this.dataInput.readByte();
                parseDataReceive();
            } catch (Exception ex) {
                Debug.e("lost connection");
                isRunning = false;
            }
        }
        try {
            dataInput.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        dispose();
    }

    private void dispose() {
        DataTransfer.releaseConnection();
    }

    public void stop() throws Exception {
        isRunning = false;
    }
}
